<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.rule_id ? $t('编辑') : $t('添加')" append-to-body :v-if="dialogVisible" :visible.sync="dialogVisible" width="500px" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :inline="true" :model="record" label-width="130px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('协议名称')" class="opcuaForm" prop="proto">
          <span style="color:#999;">{{ rule[record.proto] }}</span>
        </el-form-item>
        <el-form-item :label="$t('动作')" class="opcuaForm" prop="action">
          <el-select class="opcuaLength" v-model="record.action" ref="recordAction" size='small' filterable>
            <el-option v-for="(value, key) in actionList" :key="key" :label="$t(value)" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('消息类型')" class="opcuaForm" prop="msg_type">
          <el-select class="opcuaLength" v-model="record.msg_type" ref='msgType' size='small' filterable>
            <el-option v-for="item in msgTypeList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <div v-if="msgTypeShowList.includes(record.msg_type)">
          <el-form-item :label="$t('服务码')" class="opcuaForm" prop="service_id">
            <el-select class="opcuaLength" v-model="record.service_id" ref='serviceId' size='small' filterable>
              <el-option v-for="(value, key) in serviceIdList" :key="value" :label="key" :value="value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('匹配范围')" class="opcuaForm" prop="accept_range">
            <el-radio-group v-model="record.accept_range" @change="acceptRangeChange">
              <el-radio label="all" class="all">{{$t('所有')}}</el-radio>
              <el-radio label="single" class="single">{{$t('单个')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="record.accept_range === 'single'">
            <!-- <el-form-item :label="$t('节点类型')" class="opcuaForm" prop="node_id_mask" key="node_id_mask">
              <el-select class="opcuaLength" v-model="record.node_id_mask" size='small' filterable>
                <el-option v-for="(value, key) in nodeIdMaskList" :key="key" :label="value" :value="key">
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item :label="$t('节点标识')" class="opcuaForm" prop="node_id" key="node_id">
              <el-input v-emoji v-model="record.node_id" class="opcuaLength" ref="nodeId" size='small'></el-input>
            </el-form-item>
            <div v-if="['999999', '673', '676', '672', '675'].includes(record.service_id)">
              <el-form-item :label="$t('数据值类型')" class="opcuaForm" prop="data_mask">
                <el-select class="opcuaLength" v-model="record.data_mask" ref='dataMask' size='small' filterable @change="registerRangeChange">
                  <el-option v-for="(value, key) in dataMaskList" :key="key" :label="value" :value="key">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('取值范围')" prop="register_value_range_select" v-if="record.data_mask === '1'" key=" register_value_range_select">
                <el-select class="opcuaLength" v-model="record.register_value_range_select" ref='rangeSelect' @change="registerRangeChange" size='small' filterable>
                  <el-option v-for="(value, key) in registerValueRangeSelectList" :key="key" :label="value" :value="key">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('取值范围')" prop="value_range_start" v-if="record.data_mask !== '1'" key="value_range_start" style="margin-right:0">
                <el-input v-emoji v-model="record.value_range_start" ref="startRange" @change="registerRangeChange" style="width:117px" size='small'></el-input>
              </el-form-item>
              <el-form-item label="" v-if="record.data_mask !== '1'" style="margin-right:0">~</el-form-item>
              <el-form-item label-width="0" v-if="record.data_mask !== '1'" prop="value_range_end" key="value_range_end">
                <el-input v-emoji v-model="record.value_range_end" ref="endRange" @change="registerRangeChange" style="width:117px" size='small'></el-input>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="innerAddSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="innerAddClose">{{$t('取 消')}}</el-button>
    </span>

  </el-dialog>
</template>
<script>
import ruleArray from '../../ruleArray'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'OpcuaDialog',
  data () {
    var validateValueRangeStart = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('只能输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < -32768 || Number(value) > 32767) {
        callback(new Error(this.$t('值范围-32768~32767')))
      } else if (this.record.value_range_start && this.record.value_range_end && (Number(this.record.value_range_start) > Number(this.record.value_range_end))) {
        callback(new Error(this.$t('不能大于最大值')))
      } else {
        this.$refs.form.clearValidate(['value_range_end'])
        callback()
      }
    }
    var validateValueRangeEnd = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('只能输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < -32768 || Number(value) > 32767) {
        callback(new Error(this.$t('值范围-32768~32767')))
      } else if (this.record.value_range_start && this.record.value_range_end && (Number(this.record.value_range_start) > Number(this.record.value_range_end))) {
        callback(new Error(this.$t('不能小于最小值')))
      } else {
        this.$refs.form.clearValidate(['value_range_start'])
        callback()
      }
    }
    return {
      dialogVisible: false,
      record: {
        accept_range: 'all',
        action: 'accept',
        data_mask: '1',
        match_direction: '-',
        msg_type: 'HEL',
        node_id: '',
        node_id_mask: '1',
        proto: 'opcua',
        rule_id: null,
        service_id: '631',
        value_range: '',
        // -----
        register_value_range_select: '0',
        value_range_end: '',
        value_range_start: ''

      },
      recordCopy: {
        accept_range: 'all',
        action: 'accept',
        data_mask: '1',
        match_direction: '-',
        msg_type: 'HEL',
        node_id: '',
        node_id_mask: '1',
        proto: 'opcua',
        rule_id: null,
        service_id: '631',
        value_range: '',
        // -----
        register_value_range_select: '0',
        value_range_end: '',
        value_range_start: ''
      },
      rule: ruleArray.rule,
      msgTypeList: ruleArray.msgTypeList,
      serviceIdList: ruleArray.serviceIdList,
      msgTypeShowList: ruleArray.msgTypeShowList,
      nodeIdMaskList: ruleArray.nodeIdMaskList,
      dataMaskList: ruleArray.dataMaskList,
      actionList: { 'accept': '允许', 'alert': '告警' },
      registerValueRangeSelectList: { '0': 'false', '1': 'true' },
      showItemList: [],
      rules: {
        value_range_start: [{ required: false, validator: validateValueRangeStart, trigger: ['blur'] }],
        value_range_end: [{ required: false, validator: validateValueRangeEnd, trigger: 'blur' }]
      }
    }
  },
  computed: {
    change () {
      const { msg_type, accept_range, service_id, data_mask } = this.record
      return { msg_type, accept_range, service_id, data_mask }
    }
    // dataType () {
    //   const {  } = this.record
    //   return { service_id, data_mask }
    // }
  },
  watch: {
    change (val) {
      if (this.msgTypeShowList.includes(val.msg_type)) {
        this.$nextTick(() => {
          const selectData = ['serviceId']
          selectClass(this.$refs, selectData)
          if (val.accept_range === 'single') {
            this.$nextTick(() => {
              const data = ['nodeId']
              inputClass(this.$refs, data)
            })
            if (['999999', '673', '676', '672', '675'].includes(val.service_id)) {
              this.$nextTick(() => {
                const selectData = ['dataMask']
                selectClass(this.$refs, selectData)
              })
              if (val.data_mask === '1') {
                const selectData = ['rangeSelect']
                selectClass(this.$refs, selectData)
              } else if (val.data_mask !== '1') {
                const data = ['startRange', 'endRange']
                inputClass(this.$refs, data)
              }
            }
          }
        })
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const selectData = ['recordAction', 'msgType']
        selectClass(this.$refs, selectData)
      })
      if (data) {
        this.record = Object.assign(this.record, data)
        this.record.data_mask =  this.record.data_mask == '0' ? '1' : this.record.data_mask;
        this.record.value_range_start = this.record.data_mask === '1' ? '' : (this.record.value_range.split('~')[0] || '')
        this.record.value_range_end = this.record.data_mask === '1' ? '' : (this.record.value_range.split('~')[1] || '')
        this.record.register_value_range_select = this.record.data_mask === '1' ? (this.record.value_range.split('~')[0] || '0') : '0'
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var formData = JSON.parse(JSON.stringify(this.record))
          if (!['999999', '673', '676', '672', '675'].includes(formData.service_id) || ['HEL', 'ACK', 'ERR'].includes(formData.msg_type) || formData.accept_range === 'all') {
            formData.data_mask = '1'
            formData.register_value_range_select = '0'
            formData.value_range_end = ''
            formData.value_range_start = ''
            formData.value_range = '0~0'
          }
          if (formData.accept_range === 'all' || ['HEL', 'ACK', 'ERR'].includes(formData.msg_type)) {
            formData.node_id = ''
          }
          this.$emit('addConfigRuleMap', formData)
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.$emit('childrenClose')
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    registerRangeChange () {
      if (this.record.data_mask === '1') {
        this.record.value_range = this.record.register_value_range_select + '~0'
      } else {
        this.record.value_range = this.record.value_range_start + '~' + this.record.value_range_end
      }
    },
    acceptRangeChange () {
      this.registerRangeChange()
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    }
  }
}
</script>
<style>
.opcuaLength {
  width: 250px;
}
</style>
